package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.dto.room.RoomAddRequest;
import com.yupi.yuoj.model.dto.room.RoomQueryRequest;
import com.yupi.yuoj.model.dto.room.RoomUpdateRequest;
import com.yupi.yuoj.model.entity.Room;
import com.yupi.yuoj.model.vo.RoomVO;
import com.yupi.yuoj.service.RoomService;
import com.yupi.yuoj.service.UserService;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/room")
@Slf4j
public class RoomController {

    @Resource
    private RoomService roomService;

    @Resource
    private UserService userService;

    @PostMapping("/add")
    public BaseResponse<Long> add(@RequestBody RoomAddRequest addRequest, HttpServletRequest request) {
        if (addRequest == null || StringUtils.isBlank(addRequest.getName())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (!userService.isAdmin(request)) {
            addRequest.setHostUserId(userService.getLoginUser(request).getId());
        }
        Room entity = new Room();
        BeanUtils.copyProperties(addRequest, entity);
        if (StringUtils.isBlank(entity.getStatus())) {
            entity.setStatus("open");
        }
        boolean result = roomService.save(entity);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(entity.getId());
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> delete(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Room old = roomService.getById(deleteRequest.getId());
        ThrowUtils.throwIf(old == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅房主或管理员
        boolean isOwner = old.getHostUserId() != null && userService.getLoginUser(request).getId().equals(old.getHostUserId());
        if (!isOwner && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = roomService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> update(@RequestBody RoomUpdateRequest updateRequest, HttpServletRequest request) {
        if (updateRequest == null || updateRequest.getId() == null || updateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Room old = roomService.getById(updateRequest.getId());
        ThrowUtils.throwIf(old == null, ErrorCode.NOT_FOUND_ERROR);
        boolean isOwner = old.getHostUserId() != null && userService.getLoginUser(request).getId().equals(old.getHostUserId());
        if (!isOwner && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        Room entity = new Room();
        BeanUtils.copyProperties(updateRequest, entity);
        boolean result = roomService.updateById(entity);
        return ResultUtils.success(result);
    }

    @GetMapping("/get")
    public BaseResponse<RoomVO> get(@RequestParam("id") Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Room entity = roomService.getById(id);
        ThrowUtils.throwIf(entity == null, ErrorCode.NOT_FOUND_ERROR);
        RoomVO vo = new RoomVO();
        BeanUtils.copyProperties(entity, vo);
        return ResultUtils.success(vo);
    }

    @PostMapping("/list/page")
    public BaseResponse<Page<RoomVO>> listByPage(@RequestBody RoomQueryRequest queryRequest) {
        long current = queryRequest.getCurrent();
        long pageSize = queryRequest.getPageSize();
        QueryWrapper<Room> qw = new QueryWrapper<>();
        if (ObjectUtils.isNotEmpty(queryRequest.getId())) {
            qw.eq("id", queryRequest.getId());
        }
        if (StringUtils.isNotBlank(queryRequest.getName())) {
            qw.like("name", queryRequest.getName());
        }
        if (StringUtils.isNotBlank(queryRequest.getCode())) {
            qw.eq("code", queryRequest.getCode());
        }
        if (ObjectUtils.isNotEmpty(queryRequest.getHostUserId())) {
            qw.eq("host_user_id", queryRequest.getHostUserId());
        }
        if (StringUtils.isNotBlank(queryRequest.getStatus())) {
            qw.eq("status", queryRequest.getStatus());
        }
        Page<Room> page = roomService.page(new Page<>(current, pageSize), qw);
        Page<RoomVO> voPage = new Page<>(current, pageSize, page.getTotal());
        List<RoomVO> vos = page.getRecords().stream().map(item -> {
            RoomVO vo = new RoomVO();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());
        voPage.setRecords(vos);
        return ResultUtils.success(voPage);
    }
}

